import { cloneDeep } from "lodash-es";

interface State {
  loading: boolean;
  refresh: boolean;
  finished: boolean;
  total_page: number;
  pageSize: number;
  page: number;
}

export function useList<T, P = any>(
  request: (params: PageParams & P) => Promise<AxiosResult<PageMo<T>>>,
  getParams?: () => P
) {
  const scrollRef = ref();
  const list = ref<T[]>([]) as Ref<T[]>;
  const data = ref();
  const state = reactive<State>({
    loading: false,
    refresh: false,
    finished: false,
    total_page: 999999,
    pageSize: 15,
    page: 1
  });
  const getData = async (more = false) => {
    try {
      if (state.page > state.total_page) {
        state.finished = true;
        state.loading = false;
        return;
      }
      if (state.loading) return;
      state.loading = true;
      const pageObj: PageParams = {
        Page: state.page,
        PageSize: state.pageSize
      };
      let query: PageParams & P;
      if (getParams) {
        query = Object.assign(pageObj, getParams());
      } else {
        query = Object.assign(pageObj, {} as P);
      }
      const res = await request(query);
      state.loading = false;
      state.refresh = false;
      // 加载更多时
      if (more) {
        list.value = [...list.value, ...res.data.List];
      } else {
        list.value = res.data.List;
      }
      state.total_page = Math.ceil(res.data.Total / state.pageSize);
      if (state.page == state.total_page || res.data.Total == 0) {
        state.finished = true;
      } else {
        state.page++;
      }
      list.value = (list.value || []).map((item: T) => {
        return {
          ...item,
          Loading: false,
          Updating: false,
          Deleteing: false,
          Checked: false
        };
      });
      data.value = cloneDeep(res.data);
      await nextTick();
    } catch (error) {
      state.loading = false;
      console.log(error);
    }
  };
  const getItem = <T>() => {
    return data.value["Item"] as T;
  };

  const search = () => {
    state.page = 1;
    state.total_page = 999999;
    state.finished = false;
    list.value = [];
    nextTick(() => {
      getData();
    });
  };

  const load = () => {
    getData(true);
  };

  const refresh = () => {
    state.refresh = true;
    state.finished = false;
    state.page = 1;
    state.total_page = 999999;
    nextTick(async () => {
      getData();
    });
  };

  return {
    scrollRef,
    state,
    list,
    getData,
    search,
    load,
    refresh,
    getItem
  };
}
